﻿/**********************************************************************************
 * Project Name :   
 * Remarks      :  
 * Class Name   :  XmlTestBuilder 
 * Version      :  v1.0.0.0 
 * Author       :  Joey Liang 
 * Description  : 
 * Created Time :  2013/10/16 21:56:13
 * Update Man   :  Joey Liang
 * Update Time  :  2013/10/16 21:56:13
************************************************************************/

using System;
using System.Collections;
using System.Xml;

namespace IdleTest.Xml
{
    public class XmlTestBuilder
    {
        private XmlDocument xmlDoc;

        public string InnerXml
        {
            get { return this.xmlDoc.InnerXml; }
        }

        public XmlTestBuilder(string xmlText)
        {
            xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlText);

            isValidXmlFormat();
        }

        public XmlTestBuilder(XmlDocument xmlDoc)
        {
            if (xmlDoc == null)
                throw new NullReferenceException("构造函数的参数不能为null");

            if (isValidXmlFormat())
            {
                this.xmlDoc = xmlDoc;
            }
        }

        private bool isValidXmlFormat()
        {
            if (this.xmlDoc == null || string.IsNullOrEmpty(InnerXml))
            {
                throw new XmlException("XML未加载或不是有效的XML格式");
            }

            return true;
        }

        public XmlNodeList GetNodeList(string xpath = "")
        {
            if (string.IsNullOrEmpty(xpath))
            {
                return xmlDoc.ChildNodes;
            }

            return xmlDoc.SelectNodes(xpath);
        }

        public XmlNode GetNode(string xpath = "")
        {
            if (string.IsNullOrEmpty(xpath))
            {
                return xmlDoc.ChildNodes[0];
            }

            return xmlDoc.SelectSingleNode(xpath);
        }

        #region Static member

        private static XmlTestBuilder instance;

        public static XmlTestBuilder CreateInstance(string xmlText = "")
        {
            if (instance == null)
            {
                instance = new XmlTestBuilder(xmlText);
            }
            return instance;
        }

        public static IEnumerator GetXmlNodeList(params XmlNode[] nodes)
        {
            if (nodes == null || nodes.Length == 0)
            {
                yield return null;
            }
            else
            {
                foreach (var item in nodes)
                {
                    yield return item;
                }
            }
        }

        #endregion
    }
}
